package fun.ticsmyc.multiThread.producerConsumer;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author Ticsmyc
 * @package fun.ticsmyc.Producerconsumer
 * @date 2020-03-06 12:15
 */
public class BlockQueue  {
    private final int size;
    private List<String> list ;
    private boolean isEmpty=true;
    private boolean isFull=false;
    public volatile int listSize ;

    public BlockQueue(int size){
        this.size =size;
        list = new ArrayList<String>(size);
        listSize=0;
    }
    public int getSize(){
        return list.size();
    }

    public synchronized void put(String x) throws InterruptedException {
        while(isFull){
            System.out.println("put: 满了，进入等待状态");
            this.wait();
            System.out.println("put： 收到通知，开始生产");
        }

        list.add(x);
        System.out.println("put: 添加"+x);
        if(isEmpty){
            isEmpty=false; //不空了
            this.notifyAll(); //通知消费者可以消费了
            System.out.println("put：通知消费者消费");
        }
        if(this.getSize() == size){
            //满了
            isFull=true;
        }
        listSize = getSize();

    }

    public synchronized String get(int x) throws InterruptedException {
        while(isEmpty){
            System.err.println("get : 空着呢，进入等待状态");
            this.wait();
            System.err.println("get ： 后到消息，开始消费");
        }

        String value = list.get(x);
        System.err.println("get: 获取到 "+value);
        list.remove(x);

        //随机清空
        Random random = new Random();
        int randomInt = random.nextInt(5);
        if (randomInt == 1) {
            System.err.println("随机数等于1， 清空集合");
            list.clear();
        }
        if(isFull){
            isFull=false;
            this.notify();
            System.err.println("get：通知生产者生产");
        }
        if(this.getSize() ==0){
            isEmpty=true;
        }
        listSize = getSize();
        return value;
    }

}
